package edu.ues21.tcs.ecommerce2011.mvc.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.ues21.tcs.ecommerce2011.mvc.dao.ArticuloDAO;
import edu.ues21.tcs.ecommerce2011.mvc.dao.MarcaDAO;
import edu.ues21.tcs.ecommerce2011.mvc.model.Articulo;
import edu.ues21.tcs.ecommerce2011.mvc.model.Marca;

/**
 * 
 * @author Acunia Marco.
 */
public class EditArticuloController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
			"/BeanLocations.xml");

	ArticuloDAO aDao = (ArticuloDAO) appContext.getBean("articuloDAO");

	MarcaDAO mDao = (MarcaDAO) appContext.getBean("marcaDAO");

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String articuloStr = request.getParameter("id");

		List<Marca> listaMarcas = mDao.getAll();

		if (articuloStr != null) {

			Integer id = Integer.parseInt(articuloStr);
			Articulo articulo = aDao.getArticulo(id);

			request.setAttribute("listaMarcas", listaMarcas);
			request.setAttribute("Articulo", articulo);

			request.getRequestDispatcher("view/EditArticulo.jsp").forward(
					request, response);

		}

	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String idArticuloStr = request.getParameter("idArticulo");

		System.out.println("PASA+++++++++++++++++++++++++" + idArticuloStr);

		Integer idArticulo = Integer.parseInt(idArticuloStr);

		String nombreStr = request.getParameter("nombre");
		String propiedadStr = request.getParameter("propiedad");

		String marcaStr = request.getParameter("marca");
		System.out.println("PASA+++++++++++++++++++++++++" + marcaStr);
		Integer idMarca = Integer.parseInt(marcaStr);

		// CREO EL ARTICULO
		Articulo articulo = new Articulo();
		articulo.setIdarticulo(idArticulo);
		articulo.setNombre(nombreStr);
		articulo.setPropiedades(propiedadStr);

		aDao.save(articulo, idMarca);

		response.sendRedirect("CRUDArticulos.do");

	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}
